package lx.exalarm.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.SparseArray;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import java.io.File;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import lx.exalarm.R;
import lx.exalarm.alarm.ActionBean;
import lx.exalarm.base.BaseActivity;
import lx.exalarm.utils.ScreenUtils;
import lx.exalarm.utils.log.Log;
import lx.exalarm.view.filepicker.FilePickerDialog;
import lx.exalarm.view.filepicker.FilePickerList;
import lx.exalarm.widget.PickerDialog;

/**
 * Created by liuxu on 15-3-3.
 */
public class ActivityAction extends BaseActivity
        implements BaseActivity.ActionBarImpl, View.OnClickListener {

    public static final String EXTRA_ACTION = "extra_action_bean";

    // activity request and result code
    private static final int AC_REQUEST_CODE_PICK_MEDIA = 2; // crop image

    private static final String[] VIDEO_SUFFIX = new String[] {
            "rm", "rmvb", "avi", "mp4", "mov", "wma", "flv", "mkv",
    };
    private static final String[] AUDIO_SUFFIX = new String[] {
            "mp3", "wmv",
    };

    private ActionBean mActionBean;

    private TextView mTypeSummary;
    private TextView mIntervalSummary;
    private TextView mDuranceSummary;
    private TextView mDataSummary;

    public static void startForResult(Activity activity, int requestCode, ActionBean action) {
        Intent intent = new Intent(activity, ActivityAction.class);
        if (action != null) {
            intent.putExtra(EXTRA_ACTION, action);
        }
        activity.startActivityForResult(intent, requestCode);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_action);

        mActionBean = (ActionBean) getIntent().getSerializableExtra(EXTRA_ACTION);
        if (mActionBean == null) {
            // new alarm
            mActionBean = ActionBean.createDefaultAudioAction();
        }
        Log.d("ActivityAction, onCreate, action: " + mActionBean);

        initView();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == 0) {
            return;
        }

        switch (requestCode) {
            case AC_REQUEST_CODE_PICK_MEDIA: {
                if (data == null) {
                    return;
                }

                break;
            }

        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void initView() {
        mTypeSummary = getView(R.id.aact_type_sum);
        mIntervalSummary = getView(R.id.aact_interval_sum);
        mDuranceSummary = getView(R.id.aact_durance_sum);
        mDataSummary = getView(R.id.aact_data_sum);

        getView(R.id.aact_type).setOnClickListener(this);
        getView(R.id.aact_data).setOnClickListener(this);
        getView(R.id.aact_interval).setOnClickListener(this);
        getView(R.id.aact_durance).setOnClickListener(this);
        getView(R.id.aact_btn_confirm).setOnClickListener(this);
        getView(R.id.aact_btn_cancel).setOnClickListener(this);

        updateText();
    }

    private void updateText() {
        mTypeSummary.setText(mActionBean.getTypeString());
        mDataSummary.setText(mActionBean.getData());
        mIntervalSummary.setText(getString(
                R.string.activity_action_detail_interval_summary, mActionBean.getInterval()));
        mDuranceSummary.setText(getString(
                R.string.activity_action_detail_duration_summary, mActionBean.getDurance()));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.aact_btn_confirm: {
                Intent intent = new Intent();
                intent.putExtra(EXTRA_ACTION, mActionBean);
                setResult(RESULT_OK, intent);
                finish();
                break;
            }
            case R.id.aact_btn_cancel: {
                finish();
                break;
            }
            case R.id.aact_data: {
                //startMediaPicker();
                new PickDataDlg(this).show();
                break;
            }
            case R.id.aact_interval: {
                startIntervalPicker();
                break;
            }
            case R.id.aact_durance: {
                new PickerDialog(this, mActionBean.getDurance(), 1, 15, null,
                        new PickerDialog.ConfirmListener() {
                    @Override
                    public void onConfirm(int value) {
                        mActionBean.setDurance(value);
                        updateText();
                    }
                }).show();
                break;
            }
            case R.id.aact_type: {
                startTypePicker();
                break;
            }
        }
    }

    private int mTypePickerSelection;

    private void startTypePicker() {
        final SparseArray<Integer> typeMap = new SparseArray<>(2);
        typeMap.put(0, ActionBean.TYPE_AUDIO);
        typeMap.put(1, ActionBean.TYPE_VIDEO);
        String[] types = new String[typeMap.size()];
        int initSelect = 0;
        for (int i = 0; i < typeMap.size(); i ++) {
            int type = typeMap.get(i);
            types[i] = ActionBean.getTypeString(type);
            if (type == mActionBean.getType()) {
                initSelect = i;
            }
        }

        new AlertDialog.Builder(this)
                .setSingleChoiceItems(types, initSelect, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mTypePickerSelection = which;
                    }
                })
                .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mActionBean.setType(typeMap.get(mTypePickerSelection));
                        updateText();
                    }
                })
                .setNegativeButton(android.R.string.cancel, null)
                .create().show();
    }

    private int mIntervalPickerSelection;

    private void startIntervalPicker() {
        final int[] intervals = new int[] {
                0, 5, 10, 15, 20,
        };
        int initSelect = 0;
        String[] selections = new String[intervals.length];
        for (int i = 0; i < intervals.length; i ++) {
            selections[i] = getString(R.string.activity_action_detail_interval_selection, intervals[i]);
            if (intervals[i] == mActionBean.getInterval()) {
                initSelect = i;
            }
        }

        new AlertDialog.Builder(this)
                .setSingleChoiceItems(selections, initSelect, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mIntervalPickerSelection = which;
                    }
                })
                .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mActionBean.setInterval(intervals[mIntervalPickerSelection]);
                        updateText();
                    }
                })
                .setNegativeButton(android.R.string.cancel, null)
                .create().show();
    }

    private void startMediaPicker() {
        final Pattern pattern;
        switch (mActionBean.getType()) {
            case ActionBean.TYPE_AUDIO: {
                pattern = initPattern(AUDIO_SUFFIX);
                break;
            }
            case ActionBean.TYPE_VIDEO: {
                pattern = initPattern(VIDEO_SUFFIX);
                break;
            }
            default: {
                // TODO: support more type
                return;
            }
        }

        new FilePickerDialog.Builder(ActivityAction.this)
                .setFilePickerFilter(new FilePickerList.FilePickerFilter() {

                    @Override
                    public boolean canBeSelected(File file) {
                        if (file.isDirectory()) {
                            return false;
                        }
                        Matcher matcher = pattern.matcher(
                                file.getAbsolutePath());
                        return matcher.find();
                    }

                    @Override
                    public boolean canBeDisplayed(File file) {
                        if (file.getName().charAt(0) == '.') {
                            return false;
                        } else if (file.isDirectory()) {
                            // directory should always be displayed
                            return true;
                        } else {
                            Matcher matcher = pattern.matcher(
                                    file.getAbsolutePath());
                            return matcher.find();
                        }
                    }

                })
                .setFileSelectCallback(new FilePickerDialog.FileSelectCallback() {
                    @Override
                    public void onFileSelected(String file) {
                        if (file != null) {
                            mActionBean.setData(Uri.fromFile(new File(file)).toString());
                            updateText();
                        }
                    }
                }).create().show();
    }

    // use regex to match files with suffix
    public static Pattern initPattern(String[] suffix) {
        StringBuilder sb = new StringBuilder();
        sb.append("\\w+\\.(");
        for (int i = 0; i < suffix.length; i++) {
            String s = suffix[i];
            if (i != 0) {
                sb.append("|");
            }
            sb.append(s).append("$");
        }
        sb.append(")");
        return Pattern.compile(sb.toString(), Pattern.CASE_INSENSITIVE);
    }


    private class PickDataDlg extends AlertDialog implements View.OnClickListener {

        private PickDataDlg(Context context) {
            super(context);
        }

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.dlg_pick_data);

            Window dialogWindow = getWindow();
            WindowManager.LayoutParams lp = dialogWindow.getAttributes();
            lp.width = ScreenUtils.getScreenWidth();
            dialogWindow.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL);
            dialogWindow.setAttributes(lp);
            dialogWindow.setWindowAnimations(R.style.dlg_pick_data_anim);

            findViewById(R.id.dlg_pick_data_btn_media).setOnClickListener(this);
            findViewById(R.id.dlg_pick_data_btn_file).setOnClickListener(this);
            findViewById(R.id.dlg_pick_data_btn_cancel).setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            switch (view.getId()){
                case R.id.dlg_pick_data_btn_media: {
//                    Intent intent = new Intent(Intent.ACTION_PICK, null);
//                    intent.setDataAndType(
//                            MediaStore.Images.Media.EXTERNAL_CONTENT_URI, getMimeType());
//                    startActivityForResult(intent, AC_REQUEST_CODE_PICK_MEDIA);

                    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                    intent.setType(getMimeType());
                    startActivityForResult(
                            Intent.createChooser(intent, "Select Media"),
                            AC_REQUEST_CODE_PICK_MEDIA);
                    break;
                }
                case R.id.dlg_pick_data_btn_file: {
                    startMediaPicker();
                    break;
                }
                case R.id.dlg_pick_data_btn_cancel: {
                    break;
                }
            }
            dismiss();
        }

        private String getMimeType() {
            switch (mActionBean.getType()) {
                case ActionBean.TYPE_AUDIO: {
                    return "audio/*";
                }
                case ActionBean.TYPE_VIDEO: {
                    return "video/*";
                }
                case ActionBean.TYPE_IMAGE: {
                    return "image/*";
                }
                default:
                    return "*/*";
            }
        }
    }


}
